// Need G4P library
import g4p_controls.*;
// You can remove the PeasyCam import if you are not using
// the GViewPeasyCam control or the PeasyCam library.
import peasy.*;

import processing.serial.*;
Serial myPort;    // The serial port
int lf = 10;      // ASCII linefeed
String inString;  // Input string from serial port

int Value, preValue = 0, Debounce = 0;
boolean bfNewVal = true;

public void setup() {
  size(1200, 600, JAVA2D);
  createGUI();
  customGUI();
  fill(#14b0d1);
  textSize(150);

  // Place your setup code here
  printArray(Serial.list());  // List all the available serial ports:
  myPort = new Serial(this, Serial.list()[0], 115200); // Open the port you are using at the rate you want:
  myPort.bufferUntil(lf);
}

public void draw() {
  if (bfNewVal) {
    bfNewVal = false;
    background(230);
    text(Value, 500, 400);
    text("cm", 800, 400);
  }
}

void serialEvent(Serial p) {
  inString = p.readString();

  String tmpStr = "";
  for (int i = 0; i < 6; i++) {
    if (inString.charAt(i) == 0x20) { // 0x20 = SPACE
      break;
    }
    tmpStr = tmpStr +inString.charAt(i);
  }
  Value = int(tmpStr);

  if (Value <= 0) {
    return;
  }

  if (abs(preValue - Value) < 40) {
    preValue = Value;
    Debounce = 0;
    slider1.setValue(Value);
    println(Value, " cm");
    bfNewVal = true;
  } else {
    Debounce++;
    if (Debounce >= 3) {
      Debounce = 0;
      preValue = Value;
    }
    println(Value, " give up ", Debounce, " time(s)");
  }
}

// Use this method to add additional statements
// to customise the GUI controls
public void customGUI() {
}
